const Vue = require("vue");
const { createBundleRenderer } = require('vue-server-renderer')
const express = require("express");
const server = express();
const fs = require('fs')
const setupDevServer = require('./build/setup-dev-server')

const isProd = process.env.NODE_ENV === 'production'
const templatePath = './index.template.html'
let renderer
let onReady //返回prosime的状态。表示内部构建是否完成。


// 生产模式，直接基于已构建好的包创建渲染器 
if (isProd) {
  const serverBundle = require('./dist/vue-ssr-server-bundle.json')
  const template = fs.readFileSync(templatePath, 'utf-8')
  const clientManifest = require('./dist/vue-ssr-client-manifest.json')
  renderer = createBundleRenderer(serverBundle, {
    runInNewContext: false, // 推荐    
    template, // （可选）页面模板    
    clientManifest // （可选）客户端构建 manifest   
  })
} else {
  // 开发模式  // 打包构建（客户端 + 服务端） -> 创建渲染器 
  onReady = setupDevServer(server, (serverBundle, template, clientManifest) => {
    renderer = createBundleRenderer(serverBundle, {
      template, clientManifest
    })
  })
}

const render = async (req, res) => {
  const context = {
    url: req.url,
    meta: '',
    title: '拉勾教育'
  }
  try {
    const html = await renderer.renderToString(context)
    res.end(html)
  } catch (err) {
    res.status(500).end('Internal Server Error')
  }
}


server.get('*', isProd ? render : async (req, res) => {
  // 开发模式：等编译构建好再渲染
  await onReady //等待构建成功
  render(req, res)
})
server.use('/dist', express.static('./dist'))//物理磁盘的资源文件
server.listen(3000, () => console.log("app listening at http://localhost:3000"));

